import SearchTop from "../../components/newSearchTop.vue";
import axios from 'axios';
import Footer from "../../components/footer.vue"

import $store from "../../components/vuex.js" // 引入新建的store 变量




export default {
    components: {
        SearchTop: SearchTop,
        Footer: Footer,



    },
    data() {
        return {
            arrList: [],
            myGame: [{ img: "../../../static/img/1.png", name: "我的游戏" }, { img: "../../../static/img/4.png", name: "我的礼包" }],
            tabIndex: 0,
            myGiftTab: ["全部礼包", "已过期礼包", "未过期礼包"],
            myGiftTabIndex: 0,
            user: "",
            userName:window.sessionStorage.getItem("userName"),
            lenovoId:window.sessionStorage.getItem("lenovoId"),
            myGameSer: [],
            gameurl: "http://pitf.vgs.lenovo.com.cn",
            topLastArr: [],
            allServer: [],
            isScroll: false,
            myGift: [],
            pageNum: 1,
            myGameList: [],
            loading: "已无更多数据...",
            loadingFlase: false,
            request: true,
            scroll: false,
            //分页
            current: 1,
            showItem: 5,
            flag: true,
            allpage: 3, // 总页数
            noPage: true,
            gotoInput: 1,
            allGiftList: [],
            newData: [],
            listGame: [],
            gameArr: [],
            myGamePalyList:{},
            semyGift:[],


        }
    },
    mounted() {
        this.myGiftList();
        this.getMyList();

        this.myLastGame()


    },
    filters: { // 自定义时间过滤器
        time: function(date) {
            var date = new Date(date); //如果date为10位不需要乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
            return Y + M + D;

        },
        giftType: function(value) { // 过滤礼包类型
            if (value == '0') {
                return "免费礼包";

            } else if (value == '1') {
                return "积分礼包";

            } else if (value = '=2') {

                return "付费礼包";

            } else {
                return "礼包";
            }
        },
    },
    created() {
        //防止页面后退
        //处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外 
        function banBackSpace(e) {
            var ev = e || window.event; //获取event对象 
            var obj = ev.target || ev.srcElement; //获取事件源 

            var t = obj.type || obj.getAttribute('type'); //获取事件源类型 

            //获取作为判断条件的事件类型 
            var vReadOnly = obj.getAttribute('readonly');
            var vEnabled = obj.getAttribute('enabled');
            //处理null值情况 
            vReadOnly = (vReadOnly == null) ? false : vReadOnly;
            vEnabled = (vEnabled == null) ? true : vEnabled;

            //当敲Backspace键时，事件源类型为密码或单行、多行文本的， 
            //并且readonly属性为true或enabled属性为false的，则退格键失效 
            var flag1 = (ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") &&
                (vReadOnly == true || vEnabled != true)) ? true : false;

            //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效 
            var flag2 = (ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea") ?
                true : false;

            //判断 
            if (flag2) {
                return false;
            }
            if (flag1) {
                return false;
            }
        }

        //禁止后退键 作用于Firefox、Opera 
        document.onkeypress = banBackSpace;
        //禁止后退键 作用于IE、Chrome 
        document.onkeydown = banBackSpace;
    },
    computed: { // 计算属性

        reMyGameList: {
            get() {
                return this.myGameList;
            },
            set() {

            }

        },
        pages: {
            get: function() {
                var pag = [];
                if (this.current < this.showItem) { //如果当前的激活的项 小于要显示的条数
                    //总页数和要显示的条数那个大就显示多少条
                    var i = Math.min(this.showItem, this.allpage);
                    while (i) {
                        pag.unshift(i--);
                    }
                } else { //当前页数大于显示页数了
                    var middle = this.current - Math.floor(this.showItem / 2), //从哪里开始
                        i = this.showItem;
                    if (middle > (this.allpage - this.showItem)) {
                        middle = (this.allpage - this.showItem) + 1
                    }
                    while (i--) {
                        pag.push(middle++);
                    }
                }

                return pag
            },
            set: function(newValue) { //如果不写计算属性的set，vue会报错


            }
        },
    },
    methods: {
        //分页
        goto: function(index) {

            if (index == this.current) { // 点击当前页

                return false
            }

            if (/^[0-9]*$/.test(index) && index <= this.allpage) {
                //$(window).scrollTop(0)
                this.current = index;
                this.ajaxList(this.current)

            } else {
                this.$toast.center("请输入正确的数字")
                this.gotoInput = 1;
            }
        },
        pages: function() {
            var pag = [];
            if (this.current < this.showItem) { //如果当前的激活的项 小于要显示的条数
                //总页数和要显示的条数那个大就显示多少条
                var i = Math.min(this.showItem, this.allpage);
                while (i) {
                    pag.unshift(i--);
                }
            } else { //当前页数大于显示页数了
                var middle = this.current - Math.floor(this.showItem / 2), //从哪里开始
                    i = this.showItem;
                if (middle > (this.allpage - this.showItem)) {
                    middle = (this.allpage - this.showItem) + 1
                }
                while (i--) {
                    pag.push(middle++);
                }
            }
            return pag
        },
        ajaxList(index) {
            this.listGame = this.gameArr[index - 1][0]

        },


        handleData(data) {
            this.allpage = Math.ceil(data.length / 4)
            if (this.allpage <= 1) {
                this.noPage = false;
            }

            // 创建一个二维数组来放分组的数据
            for (var i = 0; i < this.allpage; i++) {
                let arr = []
                arr.push(data.slice(i * 4, (i + 1) * 4))
                this.gameArr[i] = arr
            }
            this.listGame = data.slice(0, 4); // 初始化数据
        },

        loginOut: function() {

            $store.commit("layerShow")

            window.sessionStorage.setItem("token", false);
        },

        tabClick(index) { // tab切换
            console.log(index)
            this.tabIndex = index;
            if (index == 1) {
                this.noPage = false;
            } else {
                this.noPage = true;
            }

        },
        giftType(index) {
            let that = this
            this.myGiftTabIndex = index;
            if(index==0){
                this.semyGift = this.myGift
            }else if(index==1){
                this.semyGift=[];
                this.myGift.map(function(item,index){
                    if(item.term=='1'){
                        that.semyGift.push(item)
                    }

                })

            }else if(index==2){
                this.semyGift=[];
                this.myGift.map(function(item,index){
                    if(item.term=='0'){
                        that.semyGift.push(item)
                    }

                })

            }else{

            }

        },
        copy(ev) {
            var Url2 = document.getElementById("text").innerText;

            var oInput = document.createElement('input');
            oInput.value = Url2;
            document.body.appendChild(oInput);
            oInput.select(); // 选择对象
            document.execCommand("Copy"); // 执行浏览器复制命令
            oInput.className = 'oInput';
            oInput.style.display = 'none';
            this.$toast.top("激活码已复制")
        },
        
        getUserInfo() { // 通过token来获取用户的基本信息
            this.token = window.sessionStorage.getItem("token")
            if (this.token) {
                this.isLogin = true
                var ts = this
                let url = "/token/user/getUserInfo?time=" + new Date().getTime() // 防止ie请求接口缓存
                this.jqajax(url, { type: "POST", dataType: "json", data: { token: ts.token } }, function(res) {
                    console.log(res)
                    ts.user = res.data
                    ts.userName = res.data.nickname
                    ts.lenovoId = res.data.lenovoId
                })
            } else {
                this.isLogin = false
            }
        },

        getMyList() {
            let url = "gift/api/webpagegame/queryCollectionGames.do?lenovoId=" + window.sessionStorage.getItem("lenovoId") + '&relativeId=48'
            let that = this;
            axios.get(url).then(function(res) {
                console.log(res.data.gameList)
                if (res.data.code == 0) {
                    that.myGameList = res.data.gameList
                }
            }, function(err) {

            })
        },
        itemOver(index, ev) {
            if(this.listGame.length>4){//  产品说大于4才显示 你是产品你说了算
                $(".myMainRight").eq(index).css("height","3.6rem")
                $(".myGameListTwo").eq(index).css("height","2rem")
                $(".myGameListTwo").eq(index).css("overflow-y","scroll")
                
            }




           this.loadingFlase = true;
           $(".loading").eq(index).text("已无更多数据");
        
           this.$set(this.myGamePalyList[index],"myPlayGameList",this.myGamePalyList[index].gameInfos)

        },

        itemOut(index, ev) {
            $(".myMainRight").eq(index).css("height","2.6rem")
            $(".myGameListTwo").eq(index).css("overflow-y","hidden")


            this.loadingFlase = false;

            this.$set(this.myGamePalyList[index],"myPlayGameList",this.myGamePalyList[index].gameInfos.slice(0,4))
            $(".myGameListTwo").scrollTop(0)

        },

        myGiftList() { // 获取我的礼包
            let url = "gift/api/giftbag/queryMyGiftBag.do?lenovoId=" + window.sessionStorage.getItem("lenovoId")
            let that = this;
            axios.get(url).then(function(res) {
                console.log(res)
                if (res.data.code == 0) {
                    that.myGift = res.data.detaileds;
                    that.semyGift = that.myGift
                }
                
            }, function(err) {

            })
        },
        myLastGame(){// 我的游戏
            let lenovoId = window.sessionStorage.getItem("lenovoId");
            let relativeId = 48
            let url = `/gift/api/webpagegame/queryMyPlayGames.do?relativeId=${relativeId}&lenovoId=${lenovoId}`
            let that=this;
            axios.get(url).then(function(res){
                 that.handleData(res.data.gameList)

                 that.myGamePalyList = res.data.gameList


                 that.myGamePalyList.map(function(item,index){

                    that.$set(item,"myPlayGameList",item.gameInfos.slice(0,4))

                 })
               

                console.log(res)

            },function(err){

            })


        },

        goGiftDeta(giftId) { // 领取当前页面的其他礼包
            /*var url =window.location.href
            console.log(window.location)
            console.log(this.$route.path)
            url=url.split("?")[0]+"?giftId="+giftId

            window.location.href=url
            //window.location.reload()*/

            this.$router.push({ path: "../newGiftDetails", query: { giftId: giftId } })
        },


        //开始游戏
        gameStart(cpId, gameName, softId, serverId, serviceName) { //  cpId 游戏名称  softId   gameId  区服id，区服名
            let that = this;
            var url = `${this.gameurl}/gameRedirect/loginGame?cp=${cpId}_GAME&game=${softId}&gameName=${gameName}&token=${window.sessionStorage.getItem("token")}`

            this.saveGame(window.sessionStorage.getItem("lenovoId"), cpId, softId, 48, serverId, serviceName, gameName)
            window.open(url)
            //reportEvent.pageStartGame(this.userId)
        },
        saveGame(lenovoId, cpId, softId, relativeId, serverId, serviceName, gameName) { // 记录玩过的游戏 联想ID cpId softId  平台编号 区服id 区服名 游戏名
            let that = this;
            if (serverId && serviceName) {
                this.resSaveGame(lenovoId, cpId, softId, relativeId, serverId, serviceName, gameName)
            } else {
                console.log(softId)
                let _url = this.gmConf.domainHttps + "unionlogin.4366.com/lenovo/gamecenter/gslist.do?jsonp&serverType=GENERAL&order=opentime:dasc&gsPageSize=5&online" + "&game=" + softId + "&gsPageNo=1"
                console.log(_url)
                that.jqajax(_url, { type: "post", dataType: "jsonp" }, function(res) {

                    var _servers = res[softId].servers;
                    var arr = []
                    for (var item in _servers) {
                        arr.push(_servers[item]);
                    }
                    that.newService = arr[0]
                    console.log(that.newService)

                    that.resSaveGame(lenovoId, cpId, softId, relativeId, that.newService.id, that.newService.name, gameName)

                });
            }

        },
        resSaveGame(lenovoId, cpId, softId, relativeId, serverId, serviceName, gameName) {
            let that = this
            let url = `/gift/api/webpagegame/collectionGame.do?lenovoId=${lenovoId}&relativeId=${relativeId}&serverId=${serverId}&softId=${softId}&serverName=${serviceName}&gameName=${gameName}&softName=${cpId}`;
            axios.get(url).then(function(res) {
                if (res.data.code == 0) {
                    //that.$toast.top("保存成功")
                } else {
                    that.$toast.center("请求错误")
                }

            }, function(err) {

            })

        },

    }

}